package persistence.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import persistence.db.DataSet;
import persistence.db.DatabaseConnector;
import persistence.model.AbstractModel;
import persistence.model.Periode;

public class PeriodeDAO extends AbstractDAO{
	
	private Periode periode;

	public PeriodeDAO() {
		setTableName("PERIODE");
	}
	
	public PeriodeDAO(Periode per) {
		this();
		periode = per;
		setId(periode.getId());
	}
	
	public Periode getPeriode() {
		return periode;
	}

	public void setPeriode(Periode periode) {
		this.periode = periode;
	}

	public DataSet all() {
		return new DataSet(this);
	}

	public AbstractModel makeModel(ResultSet rset) {
		try {
			setId(rset.getInt("id_periode"));
			String date = dateToString(rset.getDate("datePeriode"));
			return new Periode(getId(),
					date,
					rset.getInt("positionPeriode"));
		} catch (SQLException e) {
			System.out.println("makeModel error");
			e.printStackTrace();
		}
		return null;
	}

	public void save() {
		// TODO Auto-generated method stub
		String query;
		ResultSet result;
			query = "INSERT INTO " + getTableName() + " VALUES ( S_PK_"+ getTableName() +".nextval, '" +
			periode.getDatePeriode() + "', " +
			periode.getPositionPeriode() + ")";
			/* Execute la requete */
			result = DatabaseConnector.getInstance().execute(query);
			setId(this.getId()); /* Mise a jour de l'identifiant */
	}

	public void save(int id) {
		String query;
		ResultSet result;
			query = "UPDATE " + getTableName() +
			" SET datePeriode = '" + periode.getDatePeriode() +
			"', positionPeriode = " + periode.getPositionPeriode() +
			" WHERE ID_"+ getTableName() + " = "+ id;
			/* Execute la requete */
			result = DatabaseConnector.getInstance().execute(query);
	}
}
